import os
import re
from openpyxl import load_workbook

from pt1.bianli import filter_and_remove_files


def extract_time_from_filename(filename, fps):
    """从文件名中提取时间戳并转换为秒，保留三位小数"""
    match = re.search(r'time_(\d+)\.(\d+)\.jpg', filename)
    if match:
        integer_part = int(match.group(1))
        timestamp = integer_part / fps
        return f"{timestamp:.3f}"  # 格式化为保留三位小数的字符串
    return None


def process_files(directory, xlsx_path, fps):

    '''
    摄像头
    '''


    # 获取当前目标路径的名称，检查该放哪一个目录
    end_name = os.path.basename(directory)

    # 获取所有.jpg文件
    jpg_files = [f for f in os.listdir(directory) if f.lower().endswith('.jpg')]

    # 提取时间戳
    timestamps = []
    for filename in jpg_files:
        timestamp = extract_time_from_filename(filename, fps)
        if timestamp is not None:
            timestamps.append(float(timestamp))  # 将字符串转换回浮点数以便排序

    # 检查文件数量是否足够
    if len(timestamps) < 20:
        print(f"目录 {directory} 中的文件数不足20个")
        return

    # 排序时间戳
    timestamps.sort()

    # 分组并填充到Excel表格
    wb = load_workbook(xlsx_path)
    ws = wb.active

    # 解析文件名以确定目标目录路径
    if 'wired' in end_name or '有线' in end_name:
        if '720' in end_name:
            start_row = 23
            for i in range(10):
                time1 = f"{timestamps[2 * i]:.3f}"  # 格式化为保留三位小数的字符串
                time2 = f"{timestamps[2 * i + 1]:.3f}"

                ws[f'F{start_row + i}'] = time1
                ws[f'I{start_row + i}'] = time1
                ws[f'G{start_row + i}'] = time2
                ws[f'J{start_row + i}'] = time2

        elif '1080' in end_name:
            start_row = 38
            for i in range(10):
                time1 = f"{timestamps[2 * i]:.3f}"  # 格式化为保留三位小数的字符串
                time2 = f"{timestamps[2 * i + 1]:.3f}"

                ws[f'F{start_row + i}'] = time1
                ws[f'I{start_row + i}'] = time1
                ws[f'G{start_row + i}'] = time2
                ws[f'J{start_row + i}'] = time2

        elif '480' in end_name:
            start_row = 8
            for i in range(10):
                time1 = f"{timestamps[2 * i]:.3f}"  # 格式化为保留三位小数的字符串
                time2 = f"{timestamps[2 * i + 1]:.3f}"

                ws[f'F{start_row + i}'] = time1
                ws[f'I{start_row + i}'] = time1
                ws[f'G{start_row + i}'] = time2
                ws[f'J{start_row + i}'] = time2






    wb.save(xlsx_path)
    print(f"已成功将数据写入 {xlsx_path}")



def green_word_write(directory, xlsx_path, fps):
    """
    绿色文字
    将指定目录中的文件名按顺序填入Excel表格的K38到K42单元格，并且对文件名的数字部分提取出来并且除于传入的fps。

    :param directory: 要遍历的目录路径
    :param xlsx_path: 目标Excel文件路径
    :param fps: 每秒帧数
    """



    # 获取当前目标路径的名称，检查该放哪一个目录
    end_name = os.path.basename(directory)

    # 获取所有.jpg文件并按自然顺序排序
    jpg_files = [f for f in os.listdir(directory) if f.lower().endswith('.jpg')]
    jpg_files.sort(key=lambda s: [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', s)])

    # 检查文件数量是否足够
    if len(jpg_files) < 5:
        print(f"目录 {directory} 中的文件数不足5个")
        return

    # 加载Excel工作簿和工作表
    wb = load_workbook(xlsx_path)
    ws = wb.active

    if 'wired' in end_name or '有线' in end_name:
        if '720' in end_name:
            # 定义起始行号
            start_row = 23

            # 提取时间戳并填写到指定单元格
            for i in range(min(5, len(jpg_files))):  # 确保只填写最多5个文件名
                filename = jpg_files[i]
                timestamp = extract_time_from_filename(filename, fps)
                if timestamp is not None:
                    ws[f'K{start_row + i}'] = timestamp

        elif '1080' in end_name:
            # 定义起始行号
            start_row = 38

            # 提取时间戳并填写到指定单元格
            for i in range(min(5, len(jpg_files))):  # 确保只填写最多5个文件名
                filename = jpg_files[i]
                timestamp = extract_time_from_filename(filename, fps)
                if timestamp is not None:
                    ws[f'K{start_row + i}'] = timestamp

        elif '480' in end_name:
            # 定义起始行号
            start_row = 8

            # 提取时间戳并填写到指定单元格
            for i in range(min(5, len(jpg_files))):  # 确保只填写最多5个文件名
                filename = jpg_files[i]
                timestamp = extract_time_from_filename(filename, fps)
                if timestamp is not None:
                    ws[f'K{start_row + i}'] = timestamp



    # 保存修改后的Excel文件
    wb.save(xlsx_path)
    print(f"已成功将数据写入 {xlsx_path}")


def write_to_excel(data, file_path, resolution):
    """
    将列表数据写入 Excel 文件中指定的单元格范围。

    :param data: 包含 10 个数据的列表。
    :param file_path: Excel 文件路径。
    :param resolution: 分辨率，支持 '1080', '720', '480'。
    """
    # 检查输入数据是否为长度为 10 的列表
    if not isinstance(data, list) or len(data) != 10:
        raise ValueError("数据必须是包含 10 个元素的列表")

    if not os.path.exists(file_path):
        raise FileNotFoundError(f"文件 {file_path} 不存在，请检查路径是否正确。")

    # 定义分辨率对应的起始行号
    resolution_map = {
        '1080': 8,   # E8 到 E17
        '720': 23,   # E23 到 E32
        '480': 38    # E38 到 E47
    }

    # 检查分辨率是否有效
    if resolution not in resolution_map:
        raise ValueError(f"分辨率 {resolution} 无效，仅支持以下分辨率：{list(resolution_map.keys())}")

    # 加载 Excel 工作簿和工作表
    wb = load_workbook(file_path)
    ws = wb.active

    # 获取起始行号并写入数据
    start_row = resolution_map[resolution]
    for i, value in enumerate(data):
        cell = f"E{start_row + i}"  # 生成单元格地址
        ws[cell] = value

    # 保存 Excel 文件
    wb.save(file_path)
    print(f"数据已成功写入 {file_path}")

#
if __name__ == '__main__':
    process_files(fps=240, directory='/Users/zltest/testing_video_process/will_assert',
                  xlsx_path='/Users/zltest/Desktop/PT1_0312.xlsx')